// ++++++++++++++++++++++++++++++++++++++++
// 《零基础Go语言算法实战》源码
// ++++++++++++++++++++++++++++++++++++++++
// Author:廖显东（ShirDon）
// Blog:https://www.shirdon.com/
// Gitee:https://gitee.com/shirdonl/goAlgorithms.git
// Buy link :https://item.jd.com/14101229.html
// ++++++++++++++++++++++++++++++++++++++++

package main

import "fmt"

func trap(height []int) int {
	res := 0
	peakIndex := 0
	for i := 0; i < len(height); i++ {
		if height[i] > height[peakIndex] {
			peakIndex = i
		}
	}
	left := 0
	for i := 0; i < peakIndex; i++ {
		if height[i] > left {
			left = height[i]
		} else {
			res += left - height[i]
		}
	}
	right := 0
	for i := len(height) - 1; i > peakIndex; i-- {
		if height[i] > right {
			right = height[i]
		} else {
			res += right - height[i]
		}
	}
	return res
}

func main() {
	arr := []int{1, 3, 2, 4, 1, 3, 1, 4, 5, 2, 2, 1, 4, 2, 2}
	res := trap(arr)
	fmt.Println(res)
}

//$ go run interview8-3.go
//15
